package cn.edu.gznu.wecampus.core.web.annotation;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.CriteriaBuilder.In;

import org.springframework.stereotype.Component;

@Component
public class CriteriaInOperator extends AbstractCriteriaOperator {

	public CriteriaInOperator() {
		super("in");
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Predicate createPredicate(CriteriaBuilder cb, From from, String field, Object value) {
		List<Object> values = null;
		if(value instanceof List<?>) {
			values = (List<Object>) value;
		} else {
			values = new LinkedList<Object>();
			values.add(value);
		}
		Expression<?> exp = from.get(field);
		In<Object> in = cb.in(exp);
		values.forEach(v -> {
			in.value(v);
		});
		return in;
	}
}
